package com.sz.sgs.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
@Component
public class TokenUtils {

    @Value("${appID}")
    private String appID;

    @Value("${appsecret}")
    private String appsecret;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public  String getToken(){
        String url  = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appID+"&secret="+appsecret;
        String token =  stringRedisTemplate.opsForValue().get("weixin_token");
        if (token == null){
            token = HttpClientUtils.getMethod(url);
            //{"access_token":"37_NPbwAlzvwe94IVWez5lLZmOEJhMa2ZY2vLC2mPXh-bZNOjrbHFHDYbRSXlz43F-SXU_RXfy5S0XIL9JXzFqkAPCMJsjPLElTQ3VLbNNO2ViMhenK4M8VuKk2PKWOqhZbM1dorY_wMtfevEfsZZFdAFALLR","expires_in":7200}
            JSONObject json = JSON.parseObject(token); //把字符串转为Json对象；
            Object obj = json.get("access_token");
            token = obj.toString();
            System.out.println(token);
            stringRedisTemplate.opsForValue().set("weixin_token",token, 7000,TimeUnit.SECONDS);
        }
        return token;
    }
}
